package com.gem.day17;

import java.lang.reflect.*;

/**
 * 本类用来演示Java反射获取构造方法并且调用创建对象
 * 
 * @author easonsy
 * 2020年8月13日 上午9:41:54
 */
public class ReflectConstructor {
	public static void main(String[] args) {
		Class<?> c = Point.class;
		//获取所有构造方法
		Constructor<?>[] constructors = c.getConstructors();
		//Constructor<?>[] constructors = c.getDeclaredConstructors();
		//遍历
		for (Constructor<?> constructor : constructors) {
			//System.out.println(constructor);
			String result = "";
			//1.获取修饰符
			result += Modifier.toString(constructor.getModifiers()) + " ";
			//2.构造方法名
			result += processName(constructor.getName()) + "(";
			//3.参数列表
			Class<?>[] parameterTypes = constructor.getParameterTypes();
			for (int i = 0; i < parameterTypes.length; i++) {
				result += i == parameterTypes.length - 1 ? parameterTypes[i].getName()
						: parameterTypes[i].getName() + ", ";
			}
			result += "){}";
			System.out.println(result);
		}
		System.out.println("---------------------------------------------");

		//反射创建对象
		try {
			//0.[过时]Class中newInstance()方法
			//注意:此方式只能调用空参构造
			Point p0 = (Point) c.newInstance();
			System.out.println(p0);

			//1.调用空参构造创建对象
			//Constructor<?> constructor1 = c.getConstructor(new Class<?>[] {});
			Constructor<?> constructor1 = c.getConstructor();
			//constructor1.newInstance(new Object[] {});
			Point p1 = (Point) constructor1.newInstance();
			System.out.println(p1);

			//2.调用有参构造创建对象
			//Constructor<?> constructor2 = c.getConstructor(new Class<?>[] { int.class, int.class });
			Constructor<?> constructor2 = c.getConstructor(int.class, int.class);
			//Point p2 = (Point) constructor2.newInstance(new Object[] { 5, 10 });
			Point p2 = (Point) constructor2.newInstance(5, 10);
			System.out.println(p2);
		} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理全限定名
	 */
	private static String processName(String className) {
		if (className != null && className.lastIndexOf(".") != -1) {
			return className.substring(className.lastIndexOf(".") + 1);
		}
		return className;
	}
}
